package com.ruoyi.web.controller.module.event;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.event.*;
import com.ruoyi.system.service.module.event.IEventPlanTaskInfoService;
import com.ruoyi.system.service.module.event.IEventPointQrInfoService;
import com.ruoyi.system.service.module.event.IEventTerminalsService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 巡检设备Controller
 *
 * @author ruoyi
 * @date 2023-12-25
 */
@Validated
@Api(value = "巡检设备控制器", tags = {"巡检设备管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/terminals")
public class EventTerminalsController extends BaseController {

    private final IEventTerminalsService eventTerminalsService;
	private final IEventPointQrInfoService eventPointQrInfoService;
	private final IEventPlanTaskInfoService eventPlanTaskInfoService;

	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
    /**
     * 查询巡检设备列表
     */
    @ApiOperation("查询巡检设备列表")
    @PreAuthorize("@ss.hasPermi('module:terminals:list')")
    @GetMapping("/list")
    public TableDataInfo<EventTerminals> list(@Validated EventTerminals eventTerminals) {
        QueryWrapper<EventTerminals> qw = new QueryWrapper<>();
		if(eventTerminals.getGroupId()!= null){
			qw.eq("group_id", eventTerminals.getGroupId());
		}
        TableDataInfo<EventTerminals> td = PageUtils.buildDataInfo(eventTerminalsService.page(PageUtils.buildPage(),qw));
        List<EventTerminals> list = td.getRows();
		if(CollUtil.isNotEmpty(list)){
			for (EventTerminals terminals : list){
				if(StrUtil.isNotEmpty(terminals.getQrCode())){
					terminals.setQrCode(imgUrl + terminals.getQrCode());
				}
			}
		}
        return td;
    }

    /**
     * 导出巡检设备列表
     */
    @ApiOperation("导出巡检设备列表")
    @PreAuthorize("@ss.hasPermi('module:terminals:export')")
    @Log(title = "巡检设备", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventTerminals> export(@Validated EventTerminals eventTerminals) {
        List<EventTerminals> list = eventTerminalsService.list();
        ExcelUtil<EventTerminals> util = new ExcelUtil<EventTerminals>(EventTerminals.class);
        return util.exportExcel(list, "巡检设备");
    }

    /**
     * 获取巡检设备详细信息
     */
    @ApiOperation("获取巡检设备详细信息")
    @PreAuthorize("@ss.hasPermi('module:terminals:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventTerminals> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventTerminals terminals = eventTerminalsService.getById(id);
		if(terminals!=null){
			if(StrUtil.isNotEmpty(terminals.getQrCode())){
				terminals.setQrCode(imgUrl + terminals.getQrCode());
			}
		}
        return AjaxResult.success(terminals);
    }

    /**
     * 新增巡检设备
     */
    @ApiOperation("新增巡检设备")
    @PreAuthorize("@ss.hasPermi('module:terminals:add')")
    @Log(title = "巡检设备", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventTerminals eventTerminals) {
		boolean bl = eventTerminalsService.save(eventTerminals);
		try{
			String fileName = "terminal_qr_" + eventTerminals.getId() + ".jpg";
			String content = "https://www.caihengyun.com/wxmini/terminal/info?id=" + eventTerminals.getId();
			int upload_type = FileUploadUtils.TYPE_TERMINALS;
			System.out.println("content:  "+ content);
			String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content, eventTerminals.getTerminalName(), null,
				uploadPath +"/"+img_key, true, fileName, upload_type);
			eventTerminals.setQrCode(img_key);
			if (eventTerminals.getPointQrInfoId()!=null){
				EventPointQrInfo info = eventPointQrInfoService.findById(eventTerminals.getPointQrInfoId());
				if (info!=null){
					eventTerminals.setPointQrId(info.getPointQrId());
				}
			}
			eventTerminalsService.updateById(eventTerminals);
		}catch (Exception ex){
			ex.printStackTrace();
		}

        return toAjax(bl ? 1 : 0);
    }



	/**
	 * 批量新增巡检设备
	 */
	@ApiOperation("批量新增巡检设备")
	@PreAuthorize("@ss.hasPermi('module:terminals:add')")
	@Log(title = "巡检设备", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping("/bulk")
	public AjaxResult<Void> addTerminalsBulk(@Validated(AddGroup.class) @RequestBody EventTerminals eventTerminals) {
		int bl = 0;
		if (eventTerminals.getTerminalNumBegin()!=null&&eventTerminals.getTerminalNumEnd()!=null&&eventTerminals.getTerminalNumBegin()<eventTerminals.getTerminalNumEnd()){
			//循环编号
			for (int i=eventTerminals.getTerminalNumBegin();i<=eventTerminals.getTerminalNumEnd();i++){
				EventTerminals terminals = new EventTerminals();
				terminals.setTerminalName(eventTerminals.getTerminalName());
				terminals.setTerminalType(eventTerminals.getTerminalType());
				terminals.setAddress(eventTerminals.getAddress());
				terminals.setTerminalNum(eventTerminals.getTerminalNum());
				terminals.setEstateId(eventTerminals.getEstateId());
				terminals.setRemark(eventTerminals.getRemark());
				terminals.setSurveyTemplateId(eventTerminals.getSurveyTemplateId());
				terminals.setSurveyStandardId(eventTerminals.getSurveyStandardId());
				terminals.setState(eventTerminals.getState());
				terminals.setGroupId(eventTerminals.getGroupId());
				terminals.setPropertyId(eventTerminals.getPropertyId());
				terminals.setPointQrInfoId(eventTerminals.getPointQrInfoId());
				terminals.setPointQrId(eventTerminals.getPointQrId());
				bl = eventTerminalsService.addBulk(terminals,i);
				if (bl==0){
					return toAjax(bl);
				}
			}
		}else {
			return toAjax(bl);
		}
		return toAjax(bl);
	}

	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:terminals:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody EventTerminals eventTerminals) {
		if(eventTerminals.getId()!=null){
			try{
				eventTerminals = eventTerminalsService.getById(eventTerminals.getId());
				String fileName = "terminal_qr_" + eventTerminals.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/terminal/info?id=" + eventTerminals.getId();
				int upload_type = FileUploadUtils.TYPE_TERMINALS;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, eventTerminals.getTerminalName(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
				eventTerminals.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (eventTerminalsService.updateById(eventTerminals)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}


	/**
     * 修改巡检设备
     */
    @ApiOperation("修改巡检设备")
    @PreAuthorize("@ss.hasPermi('module:terminals:edit')")
    @Log(title = "巡检设备", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventTerminals eventTerminals) {
		if (eventTerminals.getPointQrInfoId()!=null){
			EventPointQrInfo info = eventPointQrInfoService.findById(eventTerminals.getPointQrInfoId());
			if (info!=null){
				eventTerminals.setPointQrId(info.getPointQrId());
			}
		}
        return toAjax(eventTerminalsService.updateById(eventTerminals) ? 1 : 0);
    }

	/**
	 * 修改巡检设备状态
	 */
	@ApiOperation("修改巡检设备")
	@PreAuthorize("@ss.hasPermi('module:terminals:edit')")
	@Log(title = "巡检设备", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/updateState")
	public AjaxResult<Void> editState(@Validated(EditGroup.class) @RequestBody EventTerminals eventTerminals) {
		EventTerminals terminals = eventTerminalsService.getById(eventTerminals.getId());
		terminals.setState(eventTerminals.getState());
		//查询所有巡更设备info
		if (eventTerminals.getState()==0){
			QueryWrapper<EventPlanTaskInfo> qw = new QueryWrapper<>();
			qw.eq("target_type",0);
			qw.eq("state",0);
			qw.eq("target_id",eventTerminals.getId());
			List<EventPlanTaskInfo> infos = eventPlanTaskInfoService.list(qw);
			for (EventPlanTaskInfo info:infos){
				info.setState(3L);
				eventPlanTaskInfoService.updateById(info);
			}
		}
		if (eventTerminals.getState()==1){
			QueryWrapper<EventPlanTaskInfo> qw = new QueryWrapper<>();
			qw.eq("target_type",0);
			qw.eq("state",3);
			qw.eq("target_id",eventTerminals.getId());
			List<EventPlanTaskInfo> infos = eventPlanTaskInfoService.list(qw);
			for (EventPlanTaskInfo info:infos){
				info.setState(0L);
				eventPlanTaskInfoService.updateById(info);
			}
		}
		return toAjax(eventTerminalsService.updateById(eventTerminals) ? 1 : 0);
	}

    /**
     * 删除巡检设备
     */
    @ApiOperation("删除巡检设备")
    @PreAuthorize("@ss.hasPermi('module:terminals:remove')")
    @Log(title = "巡检设备" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(eventTerminalsService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
